import { LoginForm, Token, User, UserProfile } from '@/types/data'
import { createSlice, PayloadAction } from '@reduxjs/toolkit'
import DataServe from '@/api/login'
import { setToken, getToken, removeToken } from '@/utils/storage'
import { Toast } from 'antd-mobile'
import type { AppDispatch } from '@/types/store'

const loginSlice = createSlice({
  name: 'login',
  initialState: {
    authInfo: getToken(),
    profile: {} as User,
    userProfile: {} as UserProfile
  },
  reducers: {
    // 使用 PayloadAction 类型声明 `action.payload` 的内容
    login: (state, action: PayloadAction<Token>) => {
      state.authInfo = action.payload
      setToken(action.payload)
    },
    setProfile(state, action: PayloadAction<User>) {
      state.profile = action.payload
    },
    setUserProfile(state, action: PayloadAction<UserProfile>) {
      state.userProfile = action.payload
    },
    logout(state) {
      removeToken()
      state.authInfo = getToken()
      state.profile = {} as User
      state.userProfile = {} as UserProfile
    }
  }
  // extraReducers: (builder) => {
  //   builder.addCase(loginAsync.fulfilled, (state, action) => {
  //     state.authInfo = action.payload
  // setToken(action.payload)
  //   })
  // } //配合createAsyncThunk处理异步操作
})

// 导出所有同步action
export const { login, setProfile, setUserProfile, logout } = loginSlice.actions

/**
 * 异步action(不使用createAsyncThunk)
 */
export const loginAsync = (payload: LoginForm) => async (dispatch: AppDispatch) => {
  const { data } = await DataServe.login(payload)
  dispatch(login(data))
}

/**
 * 异步action（使用createAsyncThunk）
 */
// export const loginAsync = createAsyncThunk('login/login', async (payload: LoginForm, thunkAPI) => {
//   const { data } = await DataServe.login(payload)
//   return data
// })

// 发送验证码
export function getCodeAsync(payload: string) {
  return async () => {
    await DataServe.getCode(payload)
    Toast.show({
      content: '发送验证码成功',
      icon: 'success'
    })
  }
}

// 获取用户信息
export function getProfileAsync() {
  return async (dispatch: AppDispatch) => {
    const { data } = await DataServe.getProfile()
    dispatch(setProfile(data))
  }
}

// 获取个人信息以便修改
export function getUserProfile() {
  return async (dispatch: AppDispatch) => {
    const { data } = await DataServe.getUserProfile()
    dispatch(setUserProfile(data))
  }
}

// 更新个人信息
export function updateUserProfile(payload: { [key: string]: string }) {
  return async (dispatch: AppDispatch) => {
    await DataServe.updateUserProfile(payload)
    // 重新获取个人信息
    dispatch(getUserProfile())
  }
}

// 更新用户头像
export function updateUserPhoto(payload: FormData) {
  return async (dispatch: AppDispatch) => {
    await DataServe.updateUserPhoto(payload)
    // 重新获取个人信息
    dispatch(getUserProfile())
  }
}

// 默认到处reducer
export default loginSlice.reducer
